package com.rongchuang.config;

import com.rongchuang.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 获取请求头中的 token
        String token = request.getHeader("Authorization");
        // 检查是否需要验证 token 的路径
        String uri = request.getRequestURI();
        if (isTokenRequired(uri)) {
            if (token == null || token.isEmpty()) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token is missing");
                return false;
            }
            // 根据 token 并获取用户 ID
            Long userId = tokenService.getUserId(token);
            if (Objects.isNull(userId)) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
                return false;
            }
            // 将用户 ID 保存到请求属性中，以便后续处理
            request.setAttribute("userId", userId);
        }
        return true;
    }

    private boolean isTokenRequired(String uri) {
        // 如果请求的路径是登录或注册等不需要 token 的路径，则返回 false
        return !(uri.startsWith("/app/login") || uri.startsWith("/app/register"));
    }
}
